/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unilearn.bo.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import unilearn.bo.PersonManagement;
import unilearn.bo.SubjectManagement;
import unilearn.util.Calc;
import unilearn.vo.Person;
import unilearn.vo.Role;
import unilearn.vo.Subject;

/**
 *
 * @author Ming
 */
public class OpenSubjectServlet extends HttpServlet {

    private SubjectManagement subjectMgt;
    private PersonManagement personMgt;
    private int rp;

    public void init() throws ServletException {
        rp = 10;
        WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
        subjectMgt = (SubjectManagement) context.getBean("subjectMgt");
        personMgt = (PersonManagement) context.getBean("personMgt");
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession();
            Person person = (Person) session.getAttribute("person");
            Role role = (Role) session.getAttribute("role");

            if ((person == null) || (role == null) || (!role.getName().equals("staff"))) {
                return;
            }

            List<Subject> subjects = subjectMgt.getSubjects(person, role);
            if ((subjects == null) || (subjects.isEmpty())) {
                throw new Exception("This person has not subject(s).");
            }

            out.print(this.buildJSON(subjects));
        } catch (Exception e) {
            System.out.println(getClass().getName() + "[OpenSubjectServlet]\n" + e.toString());
        } finally {
            out.close();
        }
    }

    private String buildJSON(List<Subject> subjects) throws Exception {
        Map<String, Object> json = new HashMap();
        List rows = new ArrayList();
        for (Subject subject : subjects) {
            Map<String, Object> row = new HashMap();
            row.put("id", subject.getSubjectCode());
            List<String> cell = new ArrayList();
            cell.add(subject.getSubjectCode());
            cell.add(subject.getName());

            Person lecturer = personMgt.getPerson(subject.getConvernorId());
            cell.add(lecturer.getFirstName() + ", " + lecturer.getLastName());
            row.put("cell", cell);

            rows.add(row);
        }

        json.put("page", 1);
        json.put("total", Calc.calcPageTotal(rp, subjects.size()));
        json.put("rows", rows);

        return JSONObject.fromObject(json).toString();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
